﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BudgetMealsModels.Abstract;
using BudgetMealsModels.Entities;

namespace BudgetMealsModels.Concrete
{
    public class EFMealRepository : IMealRepository
    {
        private EFDbContext _context = EFDbContext.Context;
        public IQueryable<Meal> Meals { get { return _context.Meals.Include("Appetizer").Include("MainCourse").Include("Dessert"); } }
        public IQueryable<User> Users { get { return _context.Users.Include("Meals"); } }

        public void SaveMeal(Meal meal, int userID)
        {
            var user = Users.FirstOrDefault(u => u.UserID == userID);
            if (meal.MealID == 0)
            {
                meal.UserCreated = user.UserName;
                meal.UserCreatedID = user.UserID;
                if (user.Meals == null)
                    user.Meals = new List<Meal>();
                user.Meals.Add(meal);
                _context.Meals.Add(meal);
            }
            else
            {
                var storedMeal = _context.Meals.FirstOrDefault(m => m.MealID == meal.MealID);

                storedMeal.Appetizer = meal.Appetizer;
                storedMeal.MainCourse = meal.MainCourse;
                storedMeal.Dessert = meal.Dessert;

                _context.Entry(storedMeal).CurrentValues.SetValues(meal);
            }

            _context.SaveChanges();
        }
        public void DeleteMeal(Meal meal, int userID)
        {
            var user = Users.FirstOrDefault(u => u.UserID == userID);

            user.Meals.Remove(meal);

            _context.Meals.Remove(meal);
            _context.SaveChanges();
        }
    }
}
